﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConMsgServer
{
    class Program
    {
        private static Socket socket=null;
        static void Main(string[] args)
        {
            Console.WriteLine("--------------------------------------启动服务--------------------------------");
            StartServer();
            Console.ReadLine();
        }

        static void StartServer()
        {
            socket=new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
            var address = IPAddress.Parse("127.0.0.1");
            var ipoint=new IPEndPoint(address,8999);
            socket.Bind(ipoint);
            socket.Listen(30);
            ThreadPool.QueueUserWorkItem((object sto) =>
            {
                var server = sto as Socket;
                Socket connection;
                while (true)
                {
                    try
                    {
                        connection = server?.Accept();
                        var clientIp = (connection?.RemoteEndPoint as IPEndPoint)?.Address;
                        var clientPort = (connection?.RemoteEndPoint as IPEndPoint)?.Port;
                        
                        string sendmsg = $"连接服务端成功: {clientIp}:{clientPort} 连接成功!";
                        byte[] arrSendMsg = Encoding.UTF8.GetBytes(sendmsg);
                        connection?.Send(arrSendMsg);
                        //接收客户端
                        ThreadPool.QueueUserWorkItem((object stos)=>
                        {
                            var reSocket = stos as Socket;
                            while (true)
                            {
                                //8Mb 数据
                                var resove = new byte[1024 * 1024 * 8 + 1];
                                try
                                {
                                    var length = reSocket?.Receive(resove);
                                    if (length > 0)
                                    {
                                        Console.WriteLine(Encoding.UTF8.GetString(resove, 0, length.Value));
                                    }
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                    break;
                                }
                            }
                        }, connection);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                        break;
                    }
                }
            },socket);
            Console.WriteLine("已启动服务");
        }
    }
}
